<?php


/**
 * Parent of models.
 *
 * @author Zsolt Lengyel
 *
 */
class ActiveRecord extends CActiveRecord{

    /**
     *
     * @var string usual filter
     */
    public $filter;


    public function save($runValidation = true, $attributes = null){

        try{
           return parent::save($runValidation, $attributes);
        }catch(CDbException $e){
            setFlash('error', $e->getMessage());
        }

        return false;
    }

    /**
     *
     * @param CDBCriteria $criteria to append filter
     * @param string $relation relation field
     * @param array $relationFields
     * @param string $filter
     * @param boolean $seeParts
     */
    protected function relationCriteria($criteria, $relation, $relationFields , $filter, $seeParts=false){


        if(strlen($filter) == 0) return;


        if(!isset($criteria->with)){
            $criteria->with = array($relation);
        }else{
            $criteria->with = array_merge($criteria->with, array($relation));
        }

        if(is_string($relationFields))
            $relationFields = array($relationFields);

        $filterCriteria = new CDbCriteria;

        if($seeParts){
            $filterParts = explode(' ', $filter);

            foreach($filterParts as $filterPart){
                foreach ($relationFields as $field){
                    $filterCriteria->addSearchCondition($relation.'.'.$field, $filterPart, true, 'or');
                }
            }

        }else{

            foreach ($relationFields as $field){
                $filterCriteria->addSearchCondition($relation.'.'.$field, $filter, true, 'or');
            }

        }

        $criteria->mergeWith($filterCriteria);

    }

    public function rules(){
        return array(
                array('filter', 'safe', 'on'=>'search')
                );
    }

    protected function searchFields(){
        return array();
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {

        $criteria=new CDbCriteria;

        foreach ($this->searchFields() as $field){
            $criteria->addSearchCondition($field, $this->filter, true, 'or');
        }

        return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
        ));
    }

}